package com.undsf.util;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Arathi on 2015/10/20.
 */
public class Value {
    protected List<String> values;

    public Value(String line){
        values = new ArrayList<>();
        init(line, ',');
    }

    public boolean addValue(String value){
        if (values == null){
            values = new ArrayList<>();
        }
        values.add(value);
        return true;
    }

    public void init(String line, char spliter){
        //使用','分割字符串
        int index = 0;
        int quotaStartIndex = -1;
        StringBuffer lastValue = new StringBuffer();
        for (index = 0; index < line.length(); index++){
            char ch = line.charAt(index);
            if (ch == '\"'){
                if (quotaStartIndex<0){
                    //引号开始
                    quotaStartIndex = index;
                }
                else{
                    //引号结束
                    quotaStartIndex = -1;
                }
            }
            if (quotaStartIndex<0 && ch == spliter){
                String lv = lastValue.toString();
                //System.out.println(lv);
                if (lv.startsWith("\"") && lv.endsWith("\"")){
                    lv = lv.substring(1, lv.length()-1);
                }
                values.add(lv);
                lastValue.delete(0, lastValue.length());
            }
            else{
                lastValue.append(ch);
            }
        }
        if (lastValue.length()>0) {
            String lv = lastValue.toString();
            //System.out.println(lv);
            if (lv.startsWith("\"") && lv.endsWith("\"")){
                lv = lv.substring(1, lv.length()-1);
            }
            values.add(lv);
            lastValue.delete(0, lastValue.length());
        }
    }

    public int getInt(int index) throws NumberFormatException{
        String valueStr = values.get(index);
        int value = Integer.parseInt(valueStr);
        return value;
    }

    public String getString(int index){
        return values.get(index);
    }

    public int getValueAmount() {
        if (values == null){
            return 0;
        }
        return values.size();
    }
}
